<template>
  <div class="app-container">
  <el-descriptions class="margin-top" title="" :column="3" :size="'mini'" border>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-user"></i>
        采购计划
      </template>
      {{this.purchase.name}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-location-outline"></i>
        截止时间
      </template>
      {{this.purchase.dueTime}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-mobile-phone"></i>
        采购需求
      </template>
          <el-tooltip class="item" effect="dark" :content="this.purchase.needHerb" placement="top-start">
            <span>{{ellipsis(this.purchase.needHerb)}}</span>
          </el-tooltip>
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-tickets"></i>
        联系人
      </template>
      {{this.purchase.contactName}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-office-building"></i>
        电话
      </template>
      {{this.purchase.contactTel}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-office-building"></i>
        发布时间
      </template>
      {{this.purchase.addTime}}
    </el-descriptions-item>
  </el-descriptions>

  <el-tabs v-model="activeIndex" type="card" @tab-click="handleClick">
    <el-tab-pane label="报价中" name="1" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已报价" name="2" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已中标" name="3" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已结束" name="4" style="width: 25%;"></el-tab-pane>
  </el-tabs>

    <div class="filter-container">
      <!-- <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleDownload()">导出</el-button> -->
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="secondRelease()">二次发布</el-button>
    </div>
  
  <el-table v-loading="listLoading" :data="purchaseManage" element-loading-text="正在查询中。。。" @selection-change="handleSelectionChange" border fit highlight-current-row>
    <el-table-column
        type="selection"
        width="50"
        :selectable="selectable"
        align="center"
        fixed="left"
        :resizable="false"
      />
      <el-table-column align="center" label="编号" prop="code" />
      <el-table-column align="center" label="药材名" prop="herbName" />
      <el-table-column align="center" label="规格" prop="specifications" />
      <el-table-column align="center" label="需求数量" prop="needAmount" />
      <el-table-column align="center" label="单位" prop="measurementUnit" />
      <el-table-column align="center" label="供应商" prop="companyName" />
      <el-table-column align="center" label="供应商电话" prop="supplyContactTel" />
      <el-table-column align="center" label="报价(元)" prop="supplyPrice"/>
      <el-table-column align="center" label="收货数量" prop="receivedAmount" />
      <el-table-column align="center" label="需求与提供差额" prop="difference" >
       <template slot-scope="scope">
          {{ scope.row.needAmount-scope.row.receivedAmount }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="送检状态" prop="checkStatus">
        <template slot-scope="scope">
          {{ checkDic[scope.row.checkStatus] }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="收据状态" prop="remarkImage">
        <template slot-scope="scope">
          {{ scope.row.remarkImage?'已上传':'未上传' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="收据上传时间" prop="remarkTime" :formatter="formatDate"/>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button v-if="scope.row.status!='0'||scope.row.status=='5'" type="primary" size="mini" @click="handleView(scope.row)">{{scope.row.checkStatus=='2'?'上传收据':'上传检验单'}}</el-button>-->
          
          <el-button v-if="scope.row.status!='0'||scope.row.status=='5'" type="primary" size="mini" @click="handleView(scope.row)">{{checkStatusDic[scope.row.checkStatus]}}</el-button>
           
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="checkStatusDic[checkStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="dataForm.checkStatus==2" label="收 据 照 片:" prop="remarkImage">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-show="dataForm.remarkImage" :src="dataForm.remarkImage" class="avatar">
            <i v-show="!dataForm.remarkImage" class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item v-else label="检 验 单 照 片:" prop="remarkImage">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-show="dataForm.remarkImage" :src="dataForm.remarkImage" class="avatar">
            <i v-show="!dataForm.remarkImage" class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="dataForm.checkStatus==2" label="收 据 单 号:" prop="remark">
          <textarea style="width: 500px;height: 70px;" v-model="dataForm.remark" maxlength="100" placeholder="收 据 单 号"  />
        </el-form-item>
        <el-form-item v-else label="检 验 单 号:" prop="remark">
          <textarea style="width: 500px;height: 70px;" v-model="dataForm.remark" maxlength="100" placeholder="检 验 单 号"  />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>


     <!-- 添加或修改对话框 -->
    <el-dialog title="二次发布" :visible.sync="boxVisible">
      <el-form ref="secondReleaseForm" :rules="rules" :model="secondReleaseForm" status-icon label-position="left" label-width="130px" style="width: 800px; margin-left:50px;">
        <el-form-item label="采购计划名" prop="name" style="width: 400px;">
          <el-input v-model="secondReleaseForm.name" />
        </el-form-item>
        <el-form-item label="报价截止时间" prop="dueTime" style="width: 400px;">
          <el-date-picker
            v-model="secondReleaseForm.dueTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            default-time="23:59:59"
          />
        </el-form-item>
        <el-form-item label="收货地址" prop="addressId" style="width: 400px;">
          <el-select @change="selectChange" v-model="secondReleaseForm.addressId" clearable style="width: 250px" class="filter-item" placeholder="收货地址">
            <el-option v-for="(item) in addressList" :key="item.id" :label="item.addressDetail" :value="item.id">
              <span style="float: left color: #8492a6; font-size: 13px">{{ item.province+item.city+item.county  }}</span>
              <span style="float: right; ">{{ item.addressDetail }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName" style="width: 400px;">
          <el-input v-model="secondReleaseForm.contactName" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel" style="width: 400px;">
          <el-input v-model="secondReleaseForm.contactTel" />
        </el-form-item>
        

        <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="herbList" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="编号" prop="code" />

      <el-table-column align="center" label="药材名" prop="herbName" />
      
      <el-table-column align="center" label="规格" prop="specifications" />
      
      <el-table-column align="center" label="数量" prop="number" >
        <template slot-scope="scope">
          {{ scope.row.needAmount-scope.row.receivedAmount }}
        </template>
      </el-table-column>
      
      <el-table-column align="center" label="单位" prop="measurementUnit" />

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="handleHerbListDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="boxVisible = false">取消</el-button>
        <el-button type="primary" @click="createData(0)">保存</el-button>
        <el-button type="primary" @click="createData(1)">保存并发布</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 145px;
  height: 145px;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar{
    width: 145px;
    height: 145px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 145px;
  height: 145px;
  line-height: 120px;
  text-align: center;
}
.avatar-uploader{
  line-height: 0px;
  width: 145px;
  height: 145px;
}
</style>

<script>
import { fetchPurchaseAndItemList,uploadAttachments,createPurchase} from '@/api/purchaseManage'
import {queryAddress} from '@/api/purchase'
import { uploadPath } from '@/api/storage'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'
import { getToken } from '@/utils/auth'

export default {
  name: 'winBidding',
  components: { Pagination },
  data() {
    return {
      thumbnail,
      toPreview,
      id:'',
      uploadPath,
      itemId:'',
      index:'',
      activeIndex: '4',
      purchase:{},
      addressList:[],
      purchaseManage: [],
      levelDic: ['个人', '饮片厂', '经销商'],
      checkStatusDic:{2:'上传收据',3:'上传检验单'},
      checkDic:['待送检','送检中','合格','不合格'],
      listLoading: true,
      boxVisible:false,
      dialogFormVisible:false,
      checkStatus:'',
      has: 'primary',
      not: 'default',
      shopList:[],
      selectList:[],
      type:0,
      queryQuery: {
        purchaseId:'',
      },
      rules: {
        remarkImage: [{ required: true, message: '照片不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '单号不能为空', trigger: 'blur' }], 
        name: [{ required: true, message: '采购计划名不能为空', trigger: 'blur' }],
        dueTime:[{ required: true, message: '报价截止时间不能为空', trigger: 'blur' }],
        addressId:[{ required: true, message: '收货地址不能为空', trigger: 'blur' }],
        },
      dataForm:{
          remarkImage:'',
          remark:''
      },
      secondReleaseForm:{

      },
      herbList:[],
      listQuery: {
        page: 1,
        limit: 20,
        type: 3,
        remark:'',
        status:'2',
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      statusDic: {
        2:'已发布'
      },
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000;
        }
      },
    }
  },
   computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.id=this.$route.query.id
      this.listQuery.id=this.$route.query.id
      this.listLoading = true
      fetchPurchaseAndItemList(this.listQuery)
        .then(response => {
          this.purchase = response.data.data.purchase
          this.purchaseManage = response.data.data.purchaseManage
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.listLoading = false
        })
    },
    ellipsis (value) {
      if (!value) return ''
      if (value.length > 20) {
        return value.slice(0,20) + '...'
      }
      return value
    },
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if(data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    createData(status) {
      var that = this
      this.$refs['secondReleaseForm'].validate(valid => {
        if (valid) {
          this.secondReleaseForm.status=status
          let data={}
          data.dataForm=this.secondReleaseForm
          data.herbList=this.herbList
          data.dataForm.inventoryplace = (that.addressList).find((arr)=>arr.id==data.dataForm.addressId).addressDetail
          if(data.herbList.length!=0){
          createPurchase(data)
            .then(response => {
              this.getList()
              this.boxVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
            }
            else{
              this.$message.error('采购药材不能为空');
            }
        }
      })
    },
    handleHerbListDelete(row){
      this.herbList.splice((this.herbList).findIndex((arr)=>arr.code==row.code), 1)
    },
    uploadPicUrl: function(response) {
      this.$set(this.dataForm,'remarkImage',response.data.url)
    },
    selectChange(e){
      if(e){
      var sub=this.addressList.findIndex((arr)=>arr.id==e)
      this.secondReleaseForm.contactName=this.addressList[sub].name
      this.secondReleaseForm.contactTel=this.addressList[sub].tel
      }
    },
    secondRelease(){
      if(this.selectList.length!=0){
        if(this.selectList.findIndex((arr) => arr.receivedAmount==arr.needAmount)==-1){
          this.$set(this.secondReleaseForm, "id", this.purchase.id);
            this.$set(this.secondReleaseForm,'name',this.purchase.name)
            this.$set(this.secondReleaseForm,'dueTime',this.purchase.dueTime)
            this.$set(this.secondReleaseForm,'needHerb',this.purchase.needHerb)
            this.$set(this.secondReleaseForm,'contactName',this.purchase.contactName)
            this.$set(this.secondReleaseForm,'contactTel',this.purchase.contactTel)
            this.$set(this.secondReleaseForm,'addressId',this.purchase.addressId)
         this.herbList=this.selectList
        this.boxVisible = true
        queryAddress()
        .then(response => {
         
          this.addressList= response.data.data
        })
        .catch(response => {
          this.$notify.error({
            title: '地址查询失败',
            message: response.data.errmsg
          })
        })
        this.$nextTick(() => {
            this.$refs['secondReleaseForm'].clearValidate()
        })
        }else{
          this.$message({
          message: '需求数量和收货数量相同，无法二次发布，请重新选择',
          type: 'warning'
        });
        }
      }else{
        this.$message({
          message: '请至少选择一个',
          type: 'warning'
        });
      }
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          uploadAttachments(this.dataForm)
             .then(() => {
              this.dialogFormVisible = false
              this.$notify.success({
                title: '上传成功'
              })
                this.getList()
            })
            .catch(response => {
              this.stepLoading=false
              this.$notify.error({
                title: '上传失败',
                message: response.data.errmsg
              })
            })
                }
            })
    },
    handleView(row,index){
       this.dataForm = Object.assign({}, row)
       this.checkStatus = this.dataForm.checkStatus
        this.dialogFormVisible = true
        this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
        })
    },
        handleClick(tab, event) {
          if(tab.name==1){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/noQuotation', query: { id: this.id }})
        }else if(tab.name==2){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/hasQuotation', query: { id: this.id }})
        }else if(tab.name==3){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/winBidding', query: { id: this.id }})
        }else if(tab.name==4){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/finish', query: { id: this.id }})
        }
      },
      selectable(row) {
      if (row.bytstatus === 4) {
        return false
      } else {
        return true
      }
    },
     // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectList = selection
    },
    // 导出的方法
    handleDownload() {
      this.downloadLoading = true
      this.listQuery.selectAll = true
      fetchPurchaseAndItemList(this.listQuery).then(response => {
        require.ensure([], () => {
          const { export_json_to_excel } = require('../../vendor/Export2Excel')// 注意这个Export2Excel路径
          const tHeader = ['药材编号', '药材名称','规格','单位','需求数量','已报价供应商数','未报价供应商数'] // 上面设置Excel的表格第一行的标题
          const filterVal = ['code', 'herbName','specifications', 'measurementUnit','needAmount','yet','sum'] // 上面的index、nickName、name是tableData里对象的属性key值
          const list = response.data.data.list // 把要导出的数据tableData存到list
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, flag?'药材品类信息':'药材品类导入模板')// 最后一个是表名字
        })
        this.downloadLoading = false
      }).catch(() => {
        this.$notify.error({
          title: '导出失败'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }

  }
}
</script>
